//
//  VehicleMaintenanceViewController.m
//  阿帕
//
//  Created 阿帕 on 2020/1/4.
//  Copyright © 2020 GCY. All rights reserved.
//

#import "WithdrawalRecordViewController.h"
#import "WithdrawalCell.h"
#import "WithdrawalConfirmView.h"
#import "WithdrawalDetailsViewController.h"


@interface WithdrawalRecordViewController ()<UITableViewDelegate, UITableViewDataSource>
{
    NSString *_gmtCreatedStart;
    NSString *_gmtCreatedEnd;
}
@property (strong , nonatomic)UITableView *tableView;

@property (strong , nonatomic)UIView *dateBgView;

@property (strong , nonatomic)NSMutableArray *dataArray;

@property (strong , nonatomic)UIImageView *foundImageView;

@property (strong , nonatomic)UIButton *addCardButton;

@property (nonatomic, assign) NSInteger pageNum;

@end

static NSString *const cellID = @"CellID";

static const CGFloat cellHeight = 180;

@implementation WithdrawalRecordViewController

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];

}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    _pageNum = 1;
    _gmtCreatedStart = @"";
    _gmtCreatedEnd = @"";
    
    [self setupBaseView];
    
    [self withdrawalListRequest];
    
}

- (void)setupBaseView {
    
    self.navigationItem.title = @"提现记录";
    
    self.view.backgroundColor = BackgroundColor;
    
    [self.view addSubview:self.tableView];
    
    [self.view addSubview:self.addCardButton];
    
    [self.view addSubview:self.dateBgView];

}

- (void)withdrawalListRequest {
    WEAKSELF
    if (_pageNum == 1) {
        [self.dataArray removeAllObjects];
    }
    
    NSDictionary *params = @{
        @"pageNum": [NSNumber numberWithInteger:_pageNum],
        @"pageSize": DEFULT_LOAD_NUM,
        @"status": _orderStatus,
        @"gmtCreatedStart": _gmtCreatedStart,
        @"gmtCreatedEnd": _gmtCreatedEnd,
        @"token":[UserDefaultUtil valueForKey:USER_TOKEN],
        @"accountType":self.accountType,
        @"accountId": self.dataDic[@"accountId"],
        @"taxLocationCode": self.dataDic[@"taxLocationCode"]
    };
    
    [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-tms-api",[ReAddressDynamic shared].baseUrl], MYBANKWITHDRAW) withParameter:params withVC:self netName:@"提现记录列表" success:^(id response, NSString *msg) {
        
        if ([response[@"records"] count] != 0) {

            [weakSelf.dataArray addObjectsFromArray:[WithdrawalRecordModel mj_objectArrayWithKeyValuesArray:response[@"records"]]];

            [weakSelf.tableView.mj_footer endRefreshing];

            weakSelf.foundImageView.hidden = YES;

        }else{
            if (_pageNum == 1) {
                weakSelf.foundImageView.hidden = NO;
            }

            [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];

        }

        [weakSelf.tableView.mj_header endRefreshing];
        [weakSelf.tableView reloadData];
        
    } failure:^(NSInteger code, NSString *msg) {
        weakSelf.foundImageView.hidden = NO;
    }];
}

//上拉刷新数据
- (void)loadNewData{
    _pageNum = 1;
    [self withdrawalListRequest];
}
- (void)loadMoreData{
    _pageNum ++;
    [self withdrawalListRequest];
}


#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    WithdrawalCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    cell.model = self.dataArray[indexPath.row];

    cell.statusButton.tag = 100 + indexPath.row;
    
    [cell.statusButton addTarget:self action:@selector(statusBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    return cell;
}

#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    WithdrawalRecordModel *model = self.dataArray[indexPath.row];
    
    return model.cellHeight;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.001f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([self.accountType intValue] == 2) {
        WithdrawalRecordModel *model = self.dataArray[indexPath.row];
       
        WithdrawalDetailsViewController *vc = [[WithdrawalDetailsViewController alloc] init];
        vc.code = model.code;
        if ([model.status isEqualToString:@"SUCCESS"] || [model.status isEqualToString:@"FAIL"]) {
            [self.navigationController pushViewController:vc animated:YES];
        }
    }
    
}

#pragma mark - 单元格上的操作按钮
- (void)statusBtnClick:(UIButton *)button {
    WEAKSELF
    WithdrawalRecordModel *model = self.dataArray[button.tag - 100];
    
    if ([model.status isEqual:@"DEALING"]) {
        //处理中 刷新状态操作
        
        NSDictionary *parmas = @{
            @"codes" : model.code,
            @"token":[UserDefaultUtil valueForKey:USER_TOKEN],
        };
        [HTTPManager putNetworkRequest:CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-tms-api",[ReAddressDynamic shared].baseUrl], MYBANKWITHDRAW_WITHDRAWQUERY) withParameter:parmas withVC:self netName:@"提现查询" success:^(id response, NSString *msg) {
            
            [XSInfoView showInfo:msg onView:weakSelf.view];
            
            [self withdrawalListRequest];
            
        } failure:^(NSInteger code, NSString *msg) {
            
        }];
        
    } else if ([model.status isEqual:@"AUDITED"]) {
        //已审核 立即打款操作 || [model.status isEqual:@"FAIL"]
//        WithdrawalConfirmView *withCofmView = [[WithdrawalConfirmView alloc] initWithFrame:CGRectMake(0, 0, ScreenW - 70, 200)];
//        withCofmView.backgroundColor = [UIColor whiteColor];
//        withCofmView.code = model.code;
//        withCofmView.phoneNum = model.partyPhone;
//        cut(withCofmView, 5);
//        [[GlobalPopUpTool sharedInstance] popUpWithView:withCofmView withViewController:nil withAnimation:YES withCanTapBgCancel:YES];
//        withCofmView.block = ^(BOOL isApplySuccess) {
//            //关闭
//            if (isApplySuccess) {
//                [[GlobalPopUpTool sharedInstance] removePopUpView];
//                [self withdrawalListRequest];
//            }
//
//        };
        
        NSDictionary *parmas = @{
            @"code" : model.code,
            @"token":[UserDefaultUtil valueForKey:USER_TOKEN],
        };
        [HTTPManager putNetworkRequest:CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-tms-api",[ReAddressDynamic shared].baseUrl], MYBANKWITHDRAW_WITHDRAWAPPLY) withParameter:parmas withVC:self netName:@"发送验证码" success:^(id response, NSString *msg) {
            
            [HTTPManager putNetworkRequest:CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-tms-api",[ReAddressDynamic shared].baseUrl], MYBANKWITHDRAW_WITHDRAWCONFIRM) withParameter:@{
                @"smsCode" : @"888888",
                @"code" : model.code,
            } withVC:self netName:@"确认提现" success:^(id response, NSString *msg) {
                
                [XSInfoView showInfo:msg onView:weakSelf.view];
                
                [self withdrawalListRequest];
                
            } failure:^(NSInteger code, NSString *msg) {
                
                [XSInfoView showInfo:msg onView:weakSelf.view];
                
            }];
            
        } failure:^(NSInteger code, NSString *msg) {
            
            [XSInfoView showInfo:msg onView:weakSelf.view];
        }];
        
    }
}

//#pragma mark - VehicleMaintenanceCellButtonDelegate
//- (void)cellButtonIndexClick:(NSInteger)index withButton:(UIButton *)button {
//
//    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:[self.tableView convertPoint:button.center fromView:button.superview]];
//    //    NSLog(@"点击了第%ld个item的第%ld个按钮",(long)indexpath.row, (index-99));
//
//    VehicleMaintenanceRecordModel *model = self.dataArray[indexPath.row];
//
//}

- (void)dateButtonClick:(UIButton *)button {
    
    if (button.tag == 200) {
        
        BRDatePickerView *datePickerView = [[BRDatePickerView alloc]initWithPickerMode:BRDatePickerModeYMD];
        datePickerView.title = @"选择开始时间";
        datePickerView.isAutoSelect = NO;
        datePickerView.showToday = NO;
        datePickerView.maxDate = [NSDate date];
        datePickerView.resultBlock = ^(NSDate *selectDate, NSString *selectValue) {
            [button setTitle:selectValue forState:UIControlStateNormal];
            _gmtCreatedStart = selectValue;
            
            [self withdrawalListRequest];
        };
        [datePickerView show:self];
        
    } else if (button.tag == 201) {
        
        BRDatePickerView *datePickerView = [[BRDatePickerView alloc]initWithPickerMode:BRDatePickerModeYMD];
        datePickerView.title = @"选择结束时间";
        datePickerView.isAutoSelect = NO;
        datePickerView.showToday = NO;
        datePickerView.resultBlock = ^(NSDate *selectDate, NSString *selectValue) {
            [button setTitle:selectValue forState:UIControlStateNormal];
            _gmtCreatedEnd = selectValue;
            
            [self withdrawalListRequest];

        };
        [datePickerView show:self];
        
    } else if (button.tag == 202) {
        
        UIButton *sbtn = [self.view viewWithTag:200];
        UIButton *ebtn = [self.view viewWithTag:201];

        _gmtCreatedStart = @"";
        _gmtCreatedEnd = @"";
        [sbtn setTitle:@"开始时间" forState:UIControlStateNormal];
        [ebtn setTitle:@"结束时间" forState:UIControlStateNormal];
        
        [self withdrawalListRequest];

    }
    
}

#pragma mark - LazyLoad
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.frame = CGRectMake(0, 60, ScreenW, ScreenH - NavHeight - 45 - 60);
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = BackgroundColor;
        
        //注册单元格
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([WithdrawalCell class]) bundle:nil] forCellReuseIdentifier:cellID];
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    }
    
    return _tableView;
}

- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}
- (UIImageView *)foundImageView {
    if (!_foundImageView) {
        _foundImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 170, 170)];
        _foundImageView.image = image(@"gcy_img_list_found");
        _foundImageView.contentMode = UIViewContentModeScaleAspectFit;
        _foundImageView.center = self.tableView.center;
        _foundImageView.cy_y -=80;
        [self.tableView addSubview:_foundImageView];
    }
    return _foundImageView;
}

- (UIView *)dateBgView {
    if (!_dateBgView) {
        _dateBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, 50)];
        _dateBgView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:_dateBgView];
        
        UIButton *startButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [startButton setTitle:@"开始时间" forState:UIControlStateNormal];
        startButton.tag = 200;
        [startButton setTitleColor:Dark_TextColor forState:UIControlStateNormal];
        startButton.titleLabel.font = font(13);
        [startButton addTarget:self action:@selector(dateButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        startButton.frame = CGRectMake(0, 0, SX(90), 50);
        [_dateBgView addSubview:startButton];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(startButton.right, 0, 20, startButton.height)];
        label.font = font(13);
        label.textColor = Dark_TextColor;
        label.text = @"至";
        label.textAlignment = NSTextAlignmentCenter;
        [_dateBgView addSubview:label];
        
        UIButton *endButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [endButton setTitle:@"结束时间" forState:UIControlStateNormal];
        endButton.tag = 201;
        endButton.titleLabel.font = font(13);
        [endButton setTitleColor:Dark_TextColor forState:UIControlStateNormal];
        [endButton addTarget:self action:@selector(dateButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        endButton.frame = CGRectMake(label.right, 0, startButton.width, startButton.height);
        [_dateBgView addSubview:endButton];
        
        UIButton *cleanButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [cleanButton setTitle:@"清空选择" forState:UIControlStateNormal];
        cleanButton.tag = 202;
        cleanButton.titleLabel.font = font(13);
        [cleanButton setTitleColor:Dark_TextColor forState:UIControlStateNormal];
        [cleanButton addTarget:self action:@selector(dateButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        cleanButton.frame = CGRectMake(endButton.right, 0, startButton.width, startButton.height);
        [_dateBgView addSubview:cleanButton];
    }
    return _dateBgView;
}

@end
